package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MutilSever {
	public static void main(String[] args) throws Exception {
		mutilSever();
	}

	private static  void mutilSever() throws Exception {
		final ServerSocket ss = new ServerSocket(8000);
		final ExecutorService pool = Executors.newCachedThreadPool();
		Runnable r = new Runnable() {
			public void run() {
				while (true) {
					try {
						Socket s = ss.accept();
						SocketHandler h = new SocketHandler(s);
						pool.execute(h);
					} catch (Exception e) {
						System.out.println("服务器已经停止");
					}
				}
			}
		};
		pool.execute(r);
	}

	static class SocketHandler implements Runnable {
		Socket s;
		BufferedReader in;
		PrintWriter out;

		public SocketHandler(Socket s) throws Exception {
			this.s = s;
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
		}

		public void run() {
			String line;
			try {
				while ((line = in.readLine()) != null) {
					System.out.println(line);
//					out.println(line);
//					out.flush();
				}
				in.close();
				out.close();
			} catch (IOException e) {
				System.out.println("客户端连接中断");
			}
		}
	}

}
